﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
using SaleManagement.Web.App_Code;


namespace SaleManagement.Web.Controls
{
  public partial class AdminMainMenu : BaseControl
  {
    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack && !Page.IsCallback)
      {
        ShowMenu();
      }
    }

    protected void rptMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
      {
        string path = Request.Url.AbsolutePath;
        string currentPage = path.Substring(path.LastIndexOf('/') + 1);
        currentPage = currentPage.Substring(0, currentPage.IndexOf(".aspx") + 5);

        XPathNavigator xmlPath = ((IXPathNavigable)e.Item.DataItem).CreateNavigator();
        XmlElement element = (XmlElement)xmlPath.UnderlyingObject;
        if (element != null)
        {
          HtmlControl lnk = e.Item.FindControl("lnkMenuItem") as HtmlControl;
          if (element.GetAttribute("Pages").Contains(currentPage))
          {
            lnk.Attributes["class"] = "active";
            SelectedMenuItem = element.GetAttribute("Id");
            SelectedMenuItemTitle = element.GetAttribute("Title");
            SelectedMenuItemIndex = e.Item.ItemIndex;
          }

          HtmlControl li = e.Item.FindControl("liMenuItem") as HtmlControl;
          HiddenField lasted = e.Item.FindControl("txtLasted") as HiddenField;
          if (element.GetAttribute("Lasted").Contains("1"))
          {
            li.Attributes["class"] = "none";
          }

          #region Check Permission
          li.Visible = false;
          string[] temp = element.GetAttribute("PermissionId").Split(',');
          foreach (string tmp in temp)
          {
            int permissionId = 0;
            int.TryParse(tmp, out permissionId);
            if (permissionId <= 0 || HasPermission(permissionId))
            {
              li.Visible = true;
              break;
            }
          }
          #endregion
        }
      }
    }
    #endregion

    #region Methods
    private void ShowMenu()
    {
      rptMenu.DataBind();
    }
    #endregion
  }
}